package com.xiyuan.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiyuan.constant.MessageConstant;
import com.xiyuan.mapper.MemoEventMapper;
import com.xiyuan.pojo.entity.MemoEvent;
import com.xiyuan.pojo.result.PageBean;
import com.xiyuan.service.MemoEventService;
import com.xiyuan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MemoEventServiceImpl implements MemoEventService {

    @Autowired
    private MemoEventMapper memoEventMapper;

    @Override
    public int insert(MemoEvent memoEvent) {
        //如果开始时间大于结束时间，则抛出异常（重新选择时间）
        if (memoEvent.getStartTime().after(memoEvent.getEndTime())) {
            throw new RuntimeException(MessageConstant.TIME_ERROR);
        }
        Map map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        memoEvent.setUserId(userId);
        return memoEventMapper.insert(memoEvent);
    }

    @Override
    public PageBean<MemoEvent> list(MemoEvent memoEvent) {
        //1. 创建PageBean对象
        PageBean pb = new PageBean<>();
        //2. 开启分页查询
        PageHelper.startPage(memoEvent.getPageNum(), memoEvent.getPageSize());
        //3.调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer loginUserId = (Integer) map.get("id");
        memoEvent.setUserId(loginUserId);
        List<MemoEvent> list = memoEventMapper.list(memoEvent);
        //Page中提供了方法，可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<MemoEvent> page = (Page<MemoEvent>) list;
        //把数据填充到PageBean对象中
        pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());
        return pb;
    }

    @Override
    public MemoEvent getById(Integer id) {
        return memoEventMapper.getById(id);
    }

    @Override
    public void delete(Integer id) {
        memoEventMapper.delete(id);
    }

    @Override
    public void update(MemoEvent memoEvent) {
        //如果开始时间大于结束时间，则抛出异常（重新选择时间）
        if (memoEvent.getStartTime().after(memoEvent.getEndTime())) {
            throw new RuntimeException(MessageConstant.TIME_ERROR);
        }
        memoEventMapper.update(memoEvent);
    }
}
